extends CharacterBody2D

@onready var hit_box: Area2D = $HitBox
@onready var weapon_manager: Node2D = %WeaponManager
@onready var health_bar: ProgressBar = %HealthBar

@export var speed = 200.0
@export var max_health :float = 100
@export var pickup_radius = 100.0
@export var level = 1

signal took_damage(amount: float, attacker: Node,current_health: float) # 受到伤害时发出的信号
signal health_changed(new_health: float) # 生命值改变时发出的信号
signal died() # 死亡时发出的信号

var health:float = max_health
#var weapons = []
#var active_weapon = null

func _ready():
	# 设置碰撞层和掩码
	# 物理碰撞体（用于墙壁等）
	set_collision_layer(1)  # 第1层：玩家物理层
	set_collision_mask(2)   # 第2层：环境物理层
	
	# 伤害检测区域（用于受伤）
	hit_box.set_collision_layer(4)    # 第3层：玩家伤害检测层
	hit_box.set_collision_mask(8)     # 第4层：敌人攻击层
	
	# 连接伤害检测信号
	hit_box.connect("area_entered", _on_hitbox_area_entered)
	
	health = max_health
	# 更新血条UI
	health_bar.value = get_health_percent()
	

# 获取输入方向
func get_input_direction():
	var direction = Vector2()
	direction.x = Input.get_action_strength("move_right") - Input.get_action_strength("move_left")
	direction.y = Input.get_action_strength("move_down") - Input.get_action_strength("move_up")
	return direction.normalized()

func _physics_process(delta):
	# 角色移动（使用物理碰撞体）
	var direction = get_input_direction()
	velocity = direction * speed
	move_and_slide()  # 这会使用主碰撞体处理物理碰撞
	

# 当HitBox（伤害检测区域）检测到敌人攻击时
func _on_hitbox_area_entered(area):
	if area.is_in_group("enemy_hitbox"):
		var enemy=area.get_parent()
		#overlapping_hitboxes.append(area)
		var damage = enemy.get_damage() if enemy.has_method("get_damage") else 0
		take_damage(damage,area)

# 处理持续伤害
#func process_damage(delta):
	#if overlapping_hitboxes.size() > 0 and !is_invincible:
		#damage_timer -= delta
		#if damage_timer <= 0:
			#damage_timer = damage_interval
			#
			## 对每个重叠的hitbox应用伤害
			#for area in overlapping_hitboxes:
				#if is_instance_valid(area) and area.is_in_group("enemy_hitbox"):
					#var enemy = area.get_parent()
					#var damage = enemy.get_damage() if enemy.has_method("get_damage") else 0
					#take_damage(damage, area)
					#break  # 每个间隔只受到一次伤害


func take_damage(amount,attacker):
	if health <= 0:
		return # 已经死亡就不再处理伤害
	health -= amount
	health_bar.value = get_health_percent()
	# 发出受伤信号
	took_damage.emit(amount,attacker,health)
	# 检查是否死亡
	if health <= 0:
		died.emit()

func die():
	$"../../GameManager".game_over()

func add_health(amount):
	health = min(health + amount, max_health)
	# 更新血条UI
	health_bar.value = get_health_percent()

func get_health_percent():
	if max_health<=0:
		return 0
	else :
		return min(health / max_health,1 ) 
		
	
